define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'editable','layui'], function ($, undefined, Backend, Table, Form,undefined,layui) {

    var Controller = {
        index: function () {
            var deptId= '';
            layui.use(function () {
                var tree = layui.tree;
                var util = layui.util;
                
                var first_status = false;
                
                tree.render({
                    elem: '#ID-tree-demo',
                    data: Config.departmentlist,
                    customName: { // 自定义 data 字段名 --- 2.8.14+
                        id: 'id',
                        title: 'name',
                        children: 'childlist'
                    },
                    showLine:true,
                    showCheckbox: true, // 是否显示复选框
                    onlyIconControl: true, // 是否仅允许节点左侧图标控制展开收缩
                    id: 'demo-id-1',
                    click: function (obj) {
                        var data = obj.data;  //获取当前点击的节点数据
//                        layer.msg('状态：' + obj.state + '<br>节点数据：' + JSON.stringify(data));
                    },
                    oncheck: function(obj){
                        if(!first_status){
                            setTimeout(function() {
                                first_status = true
                                ownGetChecked();
                            },500)
                        }else{
                            ownGetChecked();
                        }
                        
                    }
                });
                
                function ownGetChecked(){
                    var deptIdArr = [];
                    var checkedData = tree.getChecked('demo-id-1'); // 获取选中节点的数据
                    for(var i in checkedData){
                        deptIdArr.push(checkedData[i].id)
                        var tmp = checkedData[i].childlist
                        for(var y in tmp){
                            deptIdArr.push(tmp[y].id)
                            
                            var thir_tmp = tmp[y].childlist
                            for(var z in thir_tmp){
                                deptIdArr.push(thir_tmp[z].id)
                            }
                        }
                        
                        
                    }
                    deptId = deptIdArr.join(',')
                    refreshTable(deptId);
                    
                }
                
                function refreshTable(fun_deptId){
                    
                    var options = $('#table').bootstrapTable('getOptions');
                    var index_url = options.extend.index_url + '&offset=0&limit=10'
                    getShishiData(fun_deptId)
//                    if(deptId != ''){
//                        var param = {deptId:deptId}
//                        var param_ = {deptId:'in'}
//                        index_url = index_url + '&filter='+ JSON.stringify(param)+ '&op='+ JSON.stringify(param_)
//                    }
                    $.ajax({
                        url: index_url,
                        type: 'POST',
                        data : { 
                            deptId:fun_deptId
                        },
                        dataType: 'json',
                        timeout: 30000,
                        success: function(data){
                            $('#table').bootstrapTable('load', data);                            
                        },

                    })
                }
               
               



            });
            
            
            
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'zhongzhuan/fenpei/assignkehudetail/index/ids/' + Config.ids+ location.search,
//                    add_url: 'zhongzhuan/fenpei/assignkehu/add',
                    edit_url: 'zhongzhuan/fenpei/assignkehudetail/edit',
//                    del_url: 'zhongzhuan/fenpei/assignkehu/del',
                    multi_url: 'zhongzhuan/fenpei/assignkehudetail/multi',
//                    import_url: 'zhongzhuan/fenpei/assignkehu/import',
                    table: 'ec_assign_kehu',
                }
            });

            var table = $("#table");
            
            table.on('post-common-search.bs.table', function (event, table) {

                // 以下2行代码是关键，是加载完表格后，把销售搜索空实例化成selectpage格式
                var form = $("form",table.$commonsearch);
                $("input[name='deptId']",form).addClass("selectpage").data("source","zhongzhuan/ec/deparment/index").data("primaryKey","deptId").data("field","deptName");
                                
                
                Form.events.cxselect(form);
                Form.events.selectpage(form);
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'people',
                sortOrder:'desc',
                commonSearch:false,
                columns: [
                    [
                        {checkbox: true},
//                        {field: 'id', title: __('Id'),searchable:false},
                        {field: 'user_id', title:'员工', operate: 'LIKE',searchable:false,formatter: function(value, row, index) {
//                                return row.name + "[" + row.mobile +"]";
                                return row.name;
                                
                                
                            }
                        },
                        {field: 'name', title:'员工', operate: 'LIKE',visible:false,searchable:false},
//                        {field: 'deptId', title: '部门', operate: 'LIKE',visible:false},
                        {field: 'deptName', title: '部门', operate: 'LIKE',searchable:false},
//                        {field: 'deptId', title: '部门', operate: 'LIKE',visible:false},
                        {field: 'people', title: '计划分配数', operate: 'LIKE',searchable:false,editable: true,sortable:true},
                        {field: 'success_people', title: '成功分配数', operate: 'LIKE',searchable:false,sortable:true},
                        {field: 'shoudong_fenpei_people', title: '手动分配数', operate: 'LIKE',searchable:false,sortable:true},
                        {field: 'kehu_count', title: '当前客户数', operate: 'LIKE',searchable:false,sortable:true},
                        {field: 'is_shangban', title:'上班状态', searchList: {"0":'未上班',"1":'上班中'},searchable:false,sortable:true, formatter: Table.api.formatter.toggle},
//                        {field: 'auto_assign', title: '自动分配', searchList: {"0":__('auto_assign 0'),"1":__('auto_assign 1')}, formatter: Table.api.formatter.status},
//                        {field: 'auto_assign', title: '自动分配', searchList: {"0":__('auto_assign 0'),"1":__('auto_assign 1')}, formatter: Table.api.formatter.toggle},
                        {field: 'assign_status', title: '分配状态', searchable:false,searchList: {"0":'暂停中',"1":'分配中',"2":'已完成'},sortable:true,formatter: function(value, row, index) {
                                //value：intro字段的值
                                //row：当前行所有字段的数据
                                //index：当前行索引
                                //示例：
                                if(row.assign_status == 1){
                                    return "<span class='text-success'>分配中</span>";
                                }else if(row.assign_status == 2){
                                    return "<span class='text-primary'>已完成</span>";
                                }else{
                                    return "<span class='text-danger'>暂停中</span>";
                                }
                                
                            }
                        }
//                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
//                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter:Table.api.formatter.operate, }
                    ]
                ],
                queryParams:function (params) {
                    
                    
                    params.deptId  = deptId
                    console.log(params)
 
                    return params;
                }
            });
            
            getShishiData('');
            function  getShishiData(fun_deptId){
                $.ajax({
                        url: 'zhongzhuan/fenpei/assignkehudetail/assignCountShishi',
                        type: 'POST',
                        data : { 
                            deptId:fun_deptId
                        },
                        dataType: 'json',
                        timeout: 30000,
                        success:function(res){
                            $('#people_count').html(res.people_count)
                            $('#success_people_count').html(res.success_people_count)
                            console.log(res)
                        },
                        
                    })
            }
            
            $(document).on("click",'.btn-plan', function () {
                layer.prompt({
                    formType: 2,
                    value: '0',
                    title: '请输入分配数',
                    area: ['300px', '80px'] // 自定义文本域宽高
                }, function(value, index, elem){
                    layer.load(1); //风格1的加载
                    var data = $('#table').bootstrapTable('getSelections');
                    $.ajax({
                        url: 'zhongzhuan/fenpei/assignkehudetail/batchUpdatePlan',
                        type: 'POST',
                        data : { 
                            list:data,
                            people:value
                        },
                        dataType: 'json',
                        timeout: 30000,
                        success:function(res){
                            layer.msg(res.msg)
                        },
                        complete: function(data){
                            layer.closeAll()   
                            $('#table').bootstrapTable('refresh',{silent: true});
                        },

                    })
                    layer.close(index); // 关闭层
                });
                
            });
            
            
            $(document).on("click",'.btn-bushangban-status', function () {
                layer.confirm('确认要改变所选员工为不上班吗？', {
                    btn: ['确认'] //可以无限个按钮
                  }, function(index, layero){
                    layer.load(1); //风格1的加载
                    var data = $('#table').bootstrapTable('getSelections');
                    $.ajax({
                        url: 'zhongzhuan/fenpei/assignkehudetail/batchUpdateStatus',
                        type: 'POST',
                        data : { 
                            list:data,
                            is_shangban:0
                        },
                        dataType: 'json',
                        timeout: 30000,
                        success:function(res){
                            layer.msg(res.msg)
                        },
                        complete: function(data){
                            layer.closeAll()   
                            $('#table').bootstrapTable('refresh',{silent: true});
                        },

                    })
                      
                    
                     
                  });
            });
            $(document).on("click",'.btn-shangban-status', function () {
                layer.confirm('确认要改变所选员工为上班吗？', {
                    btn: ['确认'] //可以无限个按钮
                }, function(index, layero){
                     layer.load(1); //风格1的加载
                    var data = $('#table').bootstrapTable('getSelections');
                    $.ajax({
                        url: 'zhongzhuan/fenpei/assignkehudetail/batchUpdateStatus',
                        type: 'POST',
                        data : { 
                            list:data,
                            is_shangban:1
                        },
                        dataType: 'json',
                        timeout: 30000,
                        success:function(res){
                            layer.msg(res.msg)
                            
                        },
                        complete: function(data){
                            layer.closeAll()    
                            $('#table').bootstrapTable('refresh',{silent: true});
                        },

                    })
                     
                });
            });
            
            
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
